<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Map and Bar Chart</title>
    <link rel="stylesheet" href="d3-geomap/dist/d3-geomap.css">
    <style>
        #container {
            display: flex;
            justify-content: space-around; /* 在垂直方向上均匀分布子元素 */
            height: 100vh; /* 将容器高度设置为视口高度 */
        }
        #map, #bar_chart {
            flex: 1;
            min-width: 1000px;
            min-height: 0; /* 避免子元素溢出容器 */
        }
    </style>
</head>
<body>

<h1 style="text-align: center;">Map and Bar Chart</h1>

<!-- 输入框和下拉列表 -->
<div>
    <input type="number" id="yearInput" value="1800" min="1800" max="2100">
    <select id="attributeSelect">
        <option value="income">Income</option>
        <option value="population">Population</option>
        <option value="lifeExpectancy">Life Expectancy</option>
    </select>
</div>

<!-- 容器 -->
<div id="container">
    <div id="map" class="d3-geomap"></div>
    <div id="bar_chart"></div>
</div>

<!-- 加载脚本 -->
<script src="d3.v6.min.js"></script>
<script src="topojson.min.js"></script>
<script src="d3-geomap/dist/d3-geomap.min.js"></script>

<script>
    // 绘制地图
    // 加载数据并绘制地图
    const countryMapping = {
        "Afghanistan": "AFG",
        "Albania": "ALB",
        "Algeria": "DZA",
        "Andorra": "AND",
        "Angola": "AGO",
        "Antigua and Barbuda": "ATG",
        "Argentina": "ARG",
        "Armenia": "ARM",
        "Australia": "AUS",
        "Austria": "AUT",
        "Azerbaijan": "AZE",
        "Bahamas": "BHS",
        "Bahrain": "BHR",
        "Bangladesh": "BGD",
        "Barbados": "BRB",
        "Belarus": "BLR",
        "Belgium": "BEL",
        "Belize": "BLZ",
        "Benin": "BEN",
        "Bhutan": "BTN",
        "Bolivia": "BOL",
        "Bosnia and Herzegovina": "BIH",
        "Botswana": "BWA",
        "Brazil": "BRA",
        "Brunei": "BRN",
        "Bulgaria": "BGR",
        "Burkina Faso": "BFA",
        "Burundi": "BDI",
        "Cabo Verde": "CPV",
        "Cambodia": "KHM",
        "Cameroon": "CMR",
        "Canada": "CAN",
        "Central African Republic": "CAF",
        "Chad": "TCD",
        "Chile": "CHL",
        "China": "CHN",
        "Colombia": "COL",
        "Comoros": "COM",
        "Congo, Democratic Republic of the": "COD",
        "Congo, Republic of the": "COG",
        "Costa Rica": "CRI",
        "Croatia": "HRV",
        "Cuba": "CUB",
        "Cyprus": "CYP",
        "Czech Republic": "CZE",
        "Denmark": "DNK",
        "Djibouti": "DJI",
        "Dominica": "DMA",
        "Dominican Republic": "DOM",
        "East Timor": "TLS",
        "Ecuador": "ECU",
        "Egypt": "EGY",
        "El Salvador": "SLV",
        "Equatorial Guinea": "GNQ",
        "Eritrea": "ERI",
        "Estonia": "EST",
        "Eswatini": "SWZ",
        "Ethiopia": "ETH",
        "Fiji": "FJI",
        "Finland": "FIN",
        "France": "FRA",
        "Gabon": "GAB",
        "Gambia": "GMB",
        "Georgia": "GEO",
        "Germany": "DEU",
        "Ghana": "GHA",
        "Greece": "GRC",
        "Grenada": "GRD",
        "Guatemala": "GTM",
        "Guinea": "GIN",
        "Guinea-Bissau": "GNB",
        "Guyana": "GUY",
        "Haiti": "HTI",
        "Honduras": "HND",
        "Hungary": "HUN",
        "Iceland": "ISL",
        "India": "IND",
        "Indonesia": "IDN",
        "Iran": "IRN",
        "Iraq": "IRQ",
        "Ireland": "IRL",
        "Israel": "ISR",
        "Italy": "ITA",
        "Jamaica": "JAM",
        "Japan": "JPN",
        "Jordan": "JOR",
        "Kazakhstan": "KAZ",
        "Kenya": "KEN",
        "Kiribati": "KIR",
        "Korea, North": "PRK",
        "Korea, South": "KOR",
        "Kosovo": "XKX",
        "Kuwait": "KWT",
        "Kyrgyzstan": "KGZ",
        "Laos": "LAO",
        "Latvia": "LVA",
        "Lebanon": "LBN",
        "Lesotho": "LSO",
        "Liberia": "LBR",
        "Libya": "LBY",
        "Liechtenstein": "LIE",
        "Lithuania": "LTU",
        "Luxembourg": "LUX",
        "Madagascar": "MDG",
        "Malawi": "MWI",
        "Malaysia": "MYS",
        "Maldives": "MDV",
        "Mali": "MLI",
        "Malta": "MLT",
        "Marshall Islands": "MHL",
        "Mauritania": "MRT",
        "Mauritius": "MUS",
        "Mexico": "MEX",
        "Micronesia": "FSM",
        "Moldova": "MDA",
        "Monaco": "MCO",
        "Mongolia": "MNG",
        "Montenegro": "MNE",
        "Morocco": "MAR",
        "Mozambique": "MOZ",
        "Myanmar": "MMR",
        "Namibia": "NAM",
        "Nauru": "NRU",
        "Nepal": "NPL",
        "Netherlands": "NLD",
        "New Zealand": "NZL",
        "Nicaragua": "NIC",
        "Niger": "NER",
        "Nigeria": "NGA",
        "North Macedonia": "MKD",
        "Norway": "NOR",
        "Oman": "OMN",
        "Pakistan": "PAK",
        "Palau": "PLW",
        "Palestine": "PSE",
        "Panama": "PAN",
        "Papua New Guinea": "PNG",
        "Paraguay": "PRY",
        "Peru": "PER",
        "Philippines": "PHL",
        "Poland": "POL",
        "Portugal": "PRT",
        "Qatar": "QAT",
        "Romania": "ROU",
        "Russia": "RUS",
        "Rwanda": "RWA",
        "Saint Kitts and Nevis": "KNA",
        "Saint Lucia": "LCA",
        "Saint Vincent and the Grenadines": "VCT",
        "Samoa": "WSM",
        "San Marino": "SMR",
        "Sao Tome and Principe": "STP",
        "Saudi Arabia": "SAU",
        "Senegal": "SEN",
        "Serbia": "SRB",
        "Seychelles": "SYC",
        "Sierra Leone": "SLE",
        "Singapore": "SGP",
        "Slovakia": "SVK",
        "Slovenia": "SVN",
        "Solomon Islands": "SLB",
        "Somalia": "SOM",
        "South Africa": "ZAF",
        "South Sudan": "SSD",
        "Spain": "ESP",
        "Sri Lanka": "LKA",
        "Sudan": "SDN",
        "Suriname": "SUR",
        "Sweden": "SWE",
        "Switzerland": "CHE",
        "Syria": "SYR",
        "Taiwan": "TWN",
        "Tajikistan": "TJK",
        "Tanzania": "TZA",
        "Thailand": "THA",
        "Togo": "TGO",
        "Tonga": "TON",
        "Trinidad and Tobago": "TTO",
        "Tunisia": "TUN",
        "Turkey": "TUR",
        "Turkmenistan": "TKM",
        "Tuvalu": "TUV",
        "Uganda": "UGA",
        "Ukraine": "UKR",
        "United Arab Emirates": "ARE",
        "United Kingdom": "GBR",
        "United States": "USA",
        "Uruguay": "URY",
        "Uzbekistan": "UZB",
        "Vanuatu": "VUT",
        "Vatican City": "VAT",
        "Venezuela": "VEN",
        "Vietnam": "VNM",
        "Yemen": "YEM",
        "Zambia": "ZMB",
        "Zimbabwe": "ZWE"
    };

    // 绘制地图，参数为年份和属性(收入/人口/预期寿命)
    function drawMap(year, selectedAttribute) {
        d3.csv('./data/newData.csv').then(data => {
            // 根据年份过滤数据
            var filteredData = data.filter(d => d.year == year);

            // 转换国家名称为 ISO 3166-1 Alpha 3 代码
            filteredData.forEach(function (d) {
                d.iso3 = countryMapping[d.name];
            });

            // 清除地图容器中的所有元素
            var selection = d3.select('#map').selectAll("*").remove();

            // 绘制地图
            var map = d3.choropleth()
                .geofile('d3-geomap/dist/topojson/world/countries.json')
                .colors(d3.schemePaired)

                .format(d3.format(',.02f'))
                .legend(true)
                .unitId('iso3')
                .column(selectedAttribute);

            selection = d3.select('#map').datum(filteredData);
            map.draw(selection);
        });
    }

    // 设置输入框变化事件的监听器
    var yearInput = document.getElementById('yearInput');
    var attributeSelect = document.getElementById('attributeSelect');
    yearInput.addEventListener('input', function () {
        var selectedYear = parseInt(yearInput.value);
        var selectedAttribute = attributeSelect.value;
        drawMap(selectedYear, selectedAttribute);
    });
    attributeSelect.addEventListener('change', function () {
        var selectedYear = parseInt(yearInput.value);
        var selectedAttribute = attributeSelect.value;
        drawMap(selectedYear, selectedAttribute);
    });


    // -------------------------------------------------------------------//
    // 绘制柱状图
    // 设置图表的尺寸和边距
    const margin = {top: 10, right: 30, bottom: 100, left: 40},
        width = 460 - margin.left - margin.right,
        height = 450 - margin.top - margin.bottom;

    // 将 svg 对象附加到页面的 body 中
    const svg = d3.select("#bar_chart")
        .append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", `translate(${margin.left},${margin.top})`);

    // 根据选定的年份和属性更新柱形图的函数
    function updateBarChart(year, attribute) {
        // 读取 newData.csv 中的数据
        d3.csv("./data/newData.csv").then(data => {
            // 根据选定的年份过滤数据
            const filteredData = data.filter(d => d.year == year);

            // 根据地区对数据进行分组，并对属性值求和
            const summedData = d3.rollup(filteredData, v => d3.sum(v, d => +d[attribute]), d => d.region);

            // 将 summedData 转换为对象数组以便更容易操作
            const dataArray = Array.from(summedData, ([key, value]) => ({ region: key, value }));

            // X 轴
            const x = d3.scaleBand()
                .range([0, width])
                .domain(dataArray.map(d => d.region))
                .padding(0.2);
            svg.selectAll(".x-axis").remove();
            svg.append("g")
                .attr("class", "x-axis")
                .attr("transform", `translate(0, ${height})`)
                .call(d3.axisBottom(x))
                .selectAll("text")
                .attr("transform", "translate(-10,0)rotate(-45)")
                .style("text-anchor", "end");

            // Y 轴
            const y = d3.scaleLinear()
                .domain([0, d3.max(dataArray, d => d.value)])
                .range([height, 0]);
            svg.selectAll(".y-axis").remove();
            svg.append("g")
                .attr("class", "y-axis")
                .call(d3.axisLeft(y));

            // 绘制柱形
            const bars = svg.selectAll(".bar")
                .data(dataArray);
            bars.enter()
                .append("rect")
                .attr("class", "bar")
                .merge(bars)
                .attr("x", d => x(d.region))
                .attr("width", x.bandwidth())
                .attr("y", d => y(d.value))
                .attr("height", d => height - y(d.value))
                .attr("fill", "#69b3a2");

            bars.exit().remove();
        });
    }


    // trigger.
    // 获取输入框和下拉列表的引用
    var yearInput = document.getElementById('yearInput');
    var attributeSelect = document.getElementById('attributeSelect');

    // 设置输入框变化事件的监听器
    yearInput.addEventListener('input', function() {
        var selectedYear = parseInt(yearInput.value);
        var selectedAttribute = attributeSelect.value;
        drawMap(selectedYear, selectedAttribute);
        updateBarChart(selectedYear, selectedAttribute);
    });

    // 设置下拉列表变化事件的监听器
    attributeSelect.addEventListener('change', function() {
        var selectedYear = parseInt(yearInput.value);
        var selectedAttribute = attributeSelect.value;
        drawMap(selectedYear, selectedAttribute);
        updateBarChart(selectedYear, selectedAttribute);
    });


    // 初始化图像
    drawMap(1800, 'income'); // 默认显示收入数据
    updateBarChart(1800, "income");
</script>
</body>
</html>
